package input

import (
	"codeGenerator/service"
	"fmt"
	jsoniter "github.com/json-iterator/go"
	"github.com/urfave/cli/v2"
	"log"
	"os"
	"sort"
)

type Command struct {
	CodeAutoSrv *service.CodeAutoSrv
}

func NewCommand() *Command {
	return &Command{
		CodeAutoSrv: service.NewCodeAutoSrv(),
	}
}

func (cmd *Command) ParseInput() *cli.App {
	var filepath string
	app := &cli.App{
		Name:        "代码生成器",
		Usage:       "代码生成工具",
		Description: "一键生成自定义golang/java/python代码",
		Commands: []*cli.Command{
			{
				Name:    "generate",
				Aliases: []string{"g"},
				Usage:   "生成代码",
				Flags: []cli.Flag{
					&cli.StringFlag{
						Name:        "file",
						Aliases:     []string{"f"},
						Value:       "",
						Usage:       "待读取文件",
						Destination: &filepath,
						Required:    false,
					},
				},
				Action: func(c *cli.Context) error {
					fmt.Println("filepath：", filepath)

					data, err := os.ReadFile(filepath)
					if err != nil {
						return err
					}

					codeInfoList := new([]map[string]interface{})
					if err = jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(data, codeInfoList); err != nil {
						return err
					}

					cmd.CodeAutoSrv.Generator(*codeInfoList)

					return nil
				},
			},
		},
	}

	sort.Sort(cli.FlagsByName(app.Flags))
	sort.Sort(cli.CommandsByName(app.Commands))

	return app
}

func (cmd *Command) Start() {
	err := cmd.ParseInput().Run(os.Args)
	if err != nil {
		log.Fatal(err)
	}
}
